<template>
  <view :class="[variables.ns.b]">
    <l-popup :class="[variables.ns.e('popup'), variables.ns.e('prompt-popup')]" :overlay="false" v-model="state.visible" position="top">
      <view :class="[variables.ns.e('auth-prompt')]">
        {{ t('ProjectName') + t('components.choose-image.useAuthPrompt') + state.props.prompt }}
      </view>
    </l-popup>
    <l-popup :class="[variables.ns.e('popup'), variables.ns.e('select-popup')]" v-model="state.visible" position="bottom">
      <view :class="[variables.ns.e('way')]">
        <view :class="[variables.ns.e('way-item')]" v-for="item in config.selectWay" :key="item" @click="handle(item)">
          {{ t(`components.choose-image.${item}`) }}
        </view>
        <view :class="[variables.ns.e('way-item'), variables.ns.s('cancel')]" @click="closePopup">
          {{ t('other.cancel') }}
        </view>
      </view>
    </l-popup>
  </view>
</template>

<script lang="ts" setup>
import { ChooseImageNS, variables } from '.'
import { reactive } from 'vue'
import { t } from '@/locale'
import { CatchError } from '@/utils/catch-error'

defineOptions({
  name: ChooseImageNS.name
})
const props = defineProps(ChooseImageNS.props)
const state = reactive({
  visible: false,
  props: { ...props }
})
const config = {
  ce: new CatchError({ loading: { value: false } }),
  selectWay: ['album', 'camera'] as const,
}

function openPopup(p?: ChooseImageNS.Props) {
  Object.assign(state.props, props, p)
  state.props.prompt ??= t('components.choose-image.defaultPrompt')
  state.visible = true
}

function closePopup() {
  state.visible = false
}

function handle(type: typeof config.selectWay[number]) {
  config.ce.run = async () => {
    let filePaths = Array<string>()
    try {
      const { tempFilePaths } = await uni.chooseImage({
        count: state.props.uploadCount,
        sourceType: [type],
      })
      filePaths = tempFilePaths as string[]
    } catch (error) {
      throw t('components.choose-image.fail')
    }
    uni.showLoading({ title: t('components.choose-image.inProgress'), mask: true })

    await state.props.uploadSuccess?.()
    closePopup()
    CatchError.prompt(t('components.choose-image.success'))
  }
}

defineExpose({
  openPopup,
  closePopup
})
</script>